<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .t1 > li {
            height: 40px;
            line-height: 40px;
            background-color: aqua;
            margin: 5px 0px;
        }
        #showDiv {
            position: fixed;
        }
    </style>
    <script>
        // 2.鼠标悬浮在 哪个编号上就 显示 对应商品的信息
        function showProduct(pid, e){
            // console.log(pid);
            var left = e.clientX;
            var top = e.clientY;
            var showDiv = document.getElementById('showDiv');
            showDiv.style.left = left + 5 + "px";
            showDiv.style.top = top + 5 + "px";
            showDiv.style.display = "block";
            // console.log(left, top);
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function(){
                if(xhr.readyState == 4 && xhr.status == 200){
                    var obj = JSON.parse(xhr.responseText);
                    // console.log(obj);
                    var proDiv = document.getElementById("pro");
                    proDiv.innerHTML = `<div>编号:${obj.p_id}</div>
            <div>名称:${obj.p_name}</div>
            <div>简介:${obj.p_info}</div>
            <div>单价:${obj.p_price}</div>
            <div>单位:${obj.p_unit}</div>
            <div><img src="${obj.p_image_url}" style="width: 100px;" alt="no image"></div>`;
                }
            };
            xhr.open("post", "http://localhost/wbs20052/ajax/day01/getProduct.php", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.send("pid=" + pid);
        }
        /*
        3.当鼠标不在 商品 编号上时 隐藏 showDiv，否则 显示 showDiv。
        并且把 showDiv 的位置 移动到 鼠标所在位置。
        */
        function myhide(){
            // console.log("myhide");
            var showDiv = document.getElementById('showDiv');
            showDiv.style.display = "none";
        }

    </script>
</head>
<body>
    <h2>商品编号:</h2>
    <ul class="t1">
       
    </ul>
    <div id="showDiv" >
        <div>商品信息：</div>
        <div id="pro" >
            
        </div>
    </div>
    <script>
        // 1.显示所有商品编号
        var ul = document.getElementsByClassName("t1")[0];
        // 发送ajax请求
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4 && xhr.status == 200){
                var arr = JSON.parse(xhr.responseText);
                console.log(arr);
                var txt = "";
                arr.forEach(element => {
                    txt += `<li onmousemove="showProduct('${element.p_id}', event)" onmouseout="myhide()" >${element.p_id}</li>`;
                });
                ul.innerHTML = txt;
            }
        };
        xhr.open("get", "http://localhost/wbs20052/ajax/day01/findAll.php");
        xhr.send();
        
    </script>
</body>
</html>
